//=============================================================================
#include "CMap.h"

//=============================================================================
CMap::CMap() {
}

//=============================================================================
bool CMap::OnLoad(char* MapFile) {
    TileList.clear();

    FILE* FileHandle = fopen(MapFile, "r");

    if(FileHandle == NULL) {
        return false;
    }

    for(int Y = 0;Y < CMAP_HEIGHT;Y++) {
        for(int X = 0;X < CMAP_WIDTH;X++) {
            CTile tempTile;

            fscanf(FileHandle, "%d:%d ", &tempTile.TileID, &tempTile.TypeID);

            TileList.push_back(tempTile);
        }
        fscanf(FileHandle, "\n");
    }

    fclose(FileHandle);

    return true;
}

//-----------------------------------------------------------------------------
void CMap::OnRender() {
    //To Do: Calculate this value instead of setting it, duh...
    float tW = 0.015625f; // (1 / 64) duuurrrrrr

    for(int Y = 0;Y < CMAP_HEIGHT;Y++) {
        for(int X = 0;X < CMAP_WIDTH;X++) {
            int ID = X + (Y * CMAP_WIDTH);

            if(TileList[ID].TypeID == TILE_TYPE_NONE) continue;

            float tX = (TileList[ID].TileID % 64) * tW;
            float tY = (int(TileList[ID].TileID / 64)) * tW;

            //float tX = (1 % 64) * tW;
            //float tY = (int(0 / 64)) * tW;

            glBegin(GL_QUADS);
                glTexCoord2f(tX,        tY);        glVertex2f(X * TILE_SIZE,                   Y * TILE_SIZE);
                glTexCoord2f(tX + tW,   tY);        glVertex2f(X * TILE_SIZE + TILE_SIZE,       Y * TILE_SIZE);
                glTexCoord2f(tX + tW,   tY + tW);   glVertex2f(X * TILE_SIZE + TILE_SIZE,       Y * TILE_SIZE + TILE_SIZE);
                glTexCoord2f(tX,        tY + tW);   glVertex2f(X * TILE_SIZE,                   Y * TILE_SIZE + TILE_SIZE);
            glEnd();
        }
    }
}

//-----------------------------------------------------------------------------
void CMap::OnCleanup() {
}

//=============================================================================
int CMap::GetTileID(int X, int Y) {
    int ID = 0;

    ID = X / TILE_SIZE;
    ID = ID + (CMAP_WIDTH * (Y / TILE_SIZE));

    return ID;
}

//=============================================================================
